<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="106px">
    <el-form-item label="活动标题" prop="title">
      <el-input v-model="dataForm.title" placeholder="活动标题" style="width: 400px" clearable></el-input>
    </el-form-item>
    <el-form-item label="页面类型" prop="pageType">
      <el-select v-model="dataForm.pageType" disabled>
        <el-option
          v-if="pageTypeOptions"
          v-for="item in pageTypeOptions"
          :key="item.code"
          :label="item.name"
          :value="item.code">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="source类型" prop="sourceType">
      <el-radio-group v-model="dataForm.sourceType" @change="changeType()">
        <el-radio label="audio">音频</el-radio>
        <el-radio label="book">绘本</el-radio>
        <el-radio label="url">url</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="是否需要登录" prop="needLogin">
      <el-radio-group v-model="dataForm.needLogin">
        <el-radio :label="1">是</el-radio>
        <el-radio :label="0">否</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="页面链接" prop="iosRoute" v-if="dataForm.sourceType=='url'">
      <el-input v-model="dataForm.iosRoute" placeholder="请填写ios路由" style="width: 170px;" clearable></el-input>
      <el-input v-model="dataForm.hios" placeholder="请填写android路由" style="width: 180px;" clearable></el-input>
    </el-form-item>
    <el-form-item label="页面链接" prop="pId" v-if="dataForm.sourceType=='audio'">
      <el-autocomplete
        style="width: 200px;"
        v-model="audioName"
        clearable
        :hide-loading="true"
        :fetch-suggestions="querySearch"
        placeholder="请输入音频名称"
        :trigger-on-focus="false"
        @select="handleSelect">
        <template slot-scope="item">
          <div>{{item.item.name}}</div>
        </template>
      </el-autocomplete>
    </el-form-item>
    <el-form-item label="页面链接" prop="pId" v-if="dataForm.sourceType=='book'">
      <el-autocomplete
        style="width: 200px;"
        v-model="bookName"
        clearable
        :hide-loading="true"
        :fetch-suggestions="querySearchBook"
        placeholder="请输入绘本名称"
        :trigger-on-focus="false"
        @select="handleSelectBook">
        <template slot-scope="item">
          <div>{{item.item.name}}</div>
        </template>
      </el-autocomplete>
      <el-select v-model="dataForm.itemId" style="width: 200px;" v-if="dataForm.pId">
        <el-option
          v-for="item in bookItemOptions"
          :key="item.id"
          :label="item.itemName"
          :value="item.id">
        </el-option>
      </el-select>
      </el-form-item>
    <el-form-item label="背景图" prop="bgImg">
      <div class="bannerImg-wrapper pic">
        <el-upload
          style="display: inline-block;"
          ref="uploadBannerImg"
          accept=".jpg, .png, .jpeg"
          :action="uploadBannerImgUrl"
          :before-upload="beforeBannerImgUpload"
          :on-error="handleBannerImgError"
          :on-success="handleBannerImgSuccess"
          :show-file-list="false">
          <img v-if="dataForm.bgImg" :src="dataForm.bgImg" class="bannerImg">
          <i v-else class="el-icon-plus bannerImg-uploader-icon"></i>
        </el-upload>
      </div>
    </el-form-item> 
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
        uploadBannerImgUrl: this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`),
        dataForm: {
          title: '',
          pageType: 'homeBox',
          iosRoute: '',
          hios: '',
          bgImg: '',
          sourceType: 'url',
          appVersion: '',
          os: '',
          pId: '',
          itemId: '',
          status: '',
          startTime: '',
          endTime: '',
          needLogin: 0
        },
        audioName: '',
        bookName: '',
        bookItemOptions: [],
        pageTypeOptions: [{"code":"audioFix", "name":"音频活动"},
                          {"code":"bookFix", "name":"绘本活动"},
                          {"code":"homeStart", "name":"启动页面"},
                          {"code":"homeBox", "name":"首页弹窗"}],
        dataRule: {
          title: [
            { required: true, message: '活动标题不能为空', trigger: 'blur' }
          ],
          sourceType: [
            { required: true, message: 'source类型不能为空', trigger: 'blur' }
          ],
          pageType: [
            { required: true, message: '页面类型不能为空', trigger: 'blur' }
          ],
          iosRoute: [
            { required: true, message: '页面链接内容不能为空', trigger: 'blur' }
          ],
          hios: [
            { required: true, message: 'android路由不能为空', trigger: 'blur' }
          ],
          pId: [
            { required: true, message: '页面链接内容不能为空', trigger: 'change' }
          ],
          needLogin: [
            { required: true, message: '是否需要登录不能为空', trigger: 'change' }
          ],
          bgImg: [
            { required: true, message: '背景图不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.dataForm.bgImg = ''
        this.dataForm.iosRoute = ''
        this.dataForm.hios = ''
        this.audioName = ''
        this.bookName = ''
        this.dataForm.itemId = ''
        this.bookItemOptions = []
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/picbook/pbactivityconf/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm = data.data.pbActivityConf
                this.bookName = this.dataForm.pName
                this.audioName = this.dataForm.name
                if (data.data.itemSimpleView2s) {
                  this.bookItemOptions = data.data.itemSimpleView2s
                }
              }
            })
          }
        })
      },
      handleBannerImgSuccess (res, file) {
        this.dataForm.bgImg = res.url
      },
      beforeBannerImgUpload (file) {
        if (file.type.indexOf('image') < 0) {
          this.$message.error('图片格式不正确')
          return false
        }
      },
      handleBannerImgError (err, file, fileList) {
        this.$message.error('上传失败')
      },
      // 更改类型时清空页面链接内容
      changeType () {
        this.dataForm.pId = ''
        this.dataForm.itemId = ''
        this.audioName = ''
        this.bookName = ''
        this.dataForm.bgImg = ''
      },
      // 音频获取
      querySearch (queryString, cb) {
        this.$http({
          url: this.$http.adornUrl('/picbook/combobox/v2/listSimpleMedia/audio'),
          method: 'post',
          data: this.$http.adornData({
            'text': queryString
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            cb(data.data)
          } else {
            cb([])
          }
        }).catch(() => {
          cb([])
        })
      },
      handleSelect (item) {
        this.dataForm.pId = item.id
        this.audioName = item.name
      },
      // 绘本获取
      querySearchBook (queryString, cb) {
        this.$http({
          url: this.$http.adornUrl('/picbook/combobox/listSimpleBook'),
          method: 'post',
          data: this.$http.adornData({
            'text': queryString
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            cb(data.data)
          } else {
            cb([])
          }
        }).catch(() => {
          cb([])
        })
      },
      handleSelectBook (item) {
        this.dataForm.pId = item.id
        this.bookName = item.name
        this.$http({
          url: this.$http.adornUrl(`/picbook/combobox/listSimpleItem/${item.id}`),
          method: 'post',
          data: this.$http.adornData({
            'bookId': item.id
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.bookItemOptions = data.data
          } else {
            this.bookItemOptions =  []
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        if (this.dataForm.sourceType == 'url') {
          if (!this.dataForm.hios) {
            this.$message('android路由不能为空')
            return
          }
        }
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/picbook/pbactivityconf/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                pbActivityConf: this.dataForm
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  // duration: 1500,
                  duration: 500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
<style lang="less" scoped>
  .bannerImg-wrapper {
    .bannerImg-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      border: 1px solid #d9d9d9;
      border-radius: 6px;
      width: 266px;
      height: 150px;
      line-height: 150px;
      text-align: center;
    }
    .bannerImg {
      width: 266px;
      height: 150px;
      display: block;
    }
  }
</style>